/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package quanlysieuthi;
import DAO.*;
import DTO.*;
import Model.CModel;
import java.awt.Point;
import java.awt.event.ItemEvent;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
/**
 *
 * @author quangphuc
 */
public class FrmNhapHang extends javax.swing.JFrame {

    /**
     * Creates new form FrmDonHang
     */
    public FrmNhapHang(FrmMenu _menu) {
        initComponents();
        this.dtcNgay_nhap.setDateFormatString(QuanLySieuThi.formatDate);
        this.dtcNgay_tao.setDateFormatString(QuanLySieuThi.formatDate);
        this.LoadComBoBox();
        this.defaultValue();
        loadDataHoaDon();
        this.btnLuu.setEnabled(false);
        btnAddChiTiet.setEnabled(false);
        this._menu = _menu;
    }
    
    FrmMenu _menu = null;
    DecimalFormat df = new DecimalFormat("#,###");            
    /// ham khoi tao gia tri mac dinh cho cac control
    private void defaultValue(){
        this.txtNVNhap.setText(QuanLySieuThi.ho_ten);
        this.txtNVNhap.setEditable(false);
        dtcNgay_nhap.setDate(new Date());
        dtcNgay_tao.setDate(new Date());
    }
        String phieu ="PN";
    //// chứa danh sách chi tiết của hóa đơn khi thêm vào
        List<CChiTietHoaDon> listChiTiet = new ArrayList<CChiTietHoaDon>();
        CHoaDon hoadon = new CHoaDon();
        public Boolean add = false;///khi nhấn nút thêm mới thì bắt chức năng là true. Chức năng đang ở trạng thái thêm mới 1 hóa đơn
        public Boolean edit = false;///khi nhấn nút sửa bật trạng thái là true. Chức năng hiện lên đang ở trạng thái cập nhật
        public Boolean delete = false;
        CHoaDonDAO hoadonDao = new CHoaDonDAO();//khai báo tên hhoadonDao để gọi các hàm thần phần thực hiện các chức năng như load danh sách các hóa đơn
        CChiTietHoaDonDAO chitietDAO =new CChiTietHoaDonDAO();//khai báo để thực hiện các hàm thành phần chitiethoadon
        CTonKhoDAO tonkhoDAO = new CTonKhoDAO();//khai báo biến thực hiện các hàm thành phần của tonkhoDao
        List<CTon_Kho> listTonKho = new ArrayList<CTon_Kho>();//mang chua danh sách các mặt hàng tồn kho cho tất cả các kho và cửa hàng      
        CSanPhamDAO sanphamDAO = new CSanPhamDAO();//khai báo biến để thực hiện các hàm thành phần trong class CSanphamdao
        List<CSanPham> listSanPham = new ArrayList<CSanPham>();//chua danh sách các sản phẩm
        SubConfig config = SubConfig.getInstance();  //
        CKho khoCurrent = new CKho();
        CKhachHang khachHang = new CKhachHang();
        List<CKho> listKho = new ArrayList<CKho>();
        //lay danh sach khach hang
        List<CKhachHang> khach_hangList = new ArrayList<CKhachHang>();
        CKhachHangDAO khachhangDAO = new CKhachHangDAO();
        //luu san pham hien tai dang duoc chon
        CSanPham sanphamCurrent = null;
        //danh sach tinh trang
        List<CTinhTrang> ltinh_trang = new ArrayList<CTinhTrang>();
        //danh sach cac hoa don
        List<CHoaDon> lhoa_don = new ArrayList<CHoaDon>();
        int currentIndex = 0;// lưu vị trị hiện tại của dòng
        int numberRow = 0;//tổng số dòng của hóa đơn
        long id = -1;//lưu id của hóa đơn
        /// danh sach ton kho chua duoc luu
        List<CTon_Kho> l_ton_kho_i = new ArrayList<CTon_Kho>();
        /// danh sach kho da co. cap nhat lai ton kho
        List<CTon_Kho> l_ton_kho_u = new ArrayList<CTon_Kho>();
        /// mang chua chi tiet san pham
        List<CChiTietHoaDon> lcthd;
        CHoaDon hdCurrent = null;
        List<CNhanVien> lnhanvien = new ArrayList<CNhanVien>();
        List<CGiaBan>lGiaBan = new ArrayList<CGiaBan>();
        private void LoadComBoBox(){
            config.init();
            CGiaBanDAO giabanDAO = new CGiaBanDAO();
            this.lGiaBan = giabanDAO.getAll(config); 
            listSanPham = sanphamDAO.getAll(config);
            tonkhoDAO.sWhere = "  where " + String.format("thang = %s and nam = %s", QuanLySieuThi.thang,QuanLySieuThi.nam);
            listTonKho = tonkhoDAO.getAll(config);  
            khachhangDAO.sWhere = " where loai = 2";
            khach_hangList = khachhangDAO.getAll(config);
            CKhoDAO khoDAO = new CKhoDAO();
            khoDAO.sWhere = " where cua_hang = false";
            listKho = khoDAO.getAll(config);

            CTinhTrangDAO trangDAO = new CTinhTrangDAO();
            ltinh_trang = trangDAO.getAll(config);
            CNhanVienDAO nvDAO = new CNhanVienDAO();
            lnhanvien = nvDAO.getAll(config);
            config.close();
            
            this.cbbTinhTrangPhieu.removeAllItems();
            for(CTinhTrang item : ltinh_trang){
                this.cbbTinhTrangPhieu.addItem(item.getTen());
            }
            
            this.cbbSanPham.removeAllItems();
            for(CSanPham sp : listSanPham){
                this.cbbSanPham.addItem(sp.getTenSanPham());
            }

            this.cbbKhachHang.removeAllItems();
            for(CKhachHang kh : khach_hangList){
                this.cbbKhachHang.addItem(kh.getHoTen());                
            }
            this.cbbKho.removeAllItems();
            for(CKho _kho : listKho){
                this.cbbKho.addItem(_kho.getTenKho());
            }

        }

        private void loadDataHoaDon(){
            config = SubConfig.getInstance();
            config.init();
            CHoaDonDAO hoa_donDAO = new CHoaDonDAO();
            String sWhere = String.format(" where loai_phieu ='%s'",phieu);
            hoa_donDAO.sWhere = sWhere + " order by id desc ";
            lhoa_don = hoa_donDAO.getAll(config);
            numberRow = lhoa_don.size();
            this.currentIndex = 0;
            view(currentIndex);
            setEditable(false);
        }
        
       
        private void view(int index){
            hdCurrent = null;
            if(index >= 0 && index < numberRow){
                CHoaDon item = this.lhoa_don.get(index);
                hdCurrent = item;
                id = item.getId();
                CModel _model = new CModel(QuanLySieuThi.user_name);
                lcthd = _model.getChiTiet(id);
                txtRows.setText(String.format("%s/%s",index + 1,numberRow));
                dtcNgay_nhap.setDate(item.getNgayNhap());
                dtcNgay_tao.setDate(item.getNgayTao());
                Double _sum = this.tongTien(lcthd);
                int indexKho = _model.indexKho(listKho, item.getKhoId());
                if(indexKho !=-1)
                    this.cbbKho.setSelectedIndex(indexKho);
                
                int i = _model.indexNhanVien(lnhanvien, item.getNguoilapId());
                if(i!= -1){
                    CNhanVien nv = lnhanvien.get(i);
                    this.txtNVNhap.setText(nv.getHoTen());
                }
                
                i = _model.indexKhachHang(khach_hangList, item.getKhachHangId());                
                if(i != -1){
                    this.cbbKhachHang.setSelectedIndex(i);
                }
                this.txtTongTien.setText(df.format(_sum));
                this.LoadDataTable(lcthd);
            }
            else if(numberRow == 0){
                List<CChiTietHoaDon> lcthd = new ArrayList<CChiTietHoaDon>();
                this.LoadDataTable(lcthd);                
                txtRows.setText(String.format("0/0"));
                this.btnSua.setEnabled(false);
            }
        }                     
        private void LoadDataTable(List<CChiTietHoaDon> list){
            Vector<Vector> result = new Vector<Vector>();
            int stt = 1;
            for(CChiTietHoaDon item :list){
                Vector<String>row = new Vector<String>();
                row.addElement("" + stt);
                row.addElement("" + item.getTenSanPham());
                row.addElement(""+item.getSoLuong());
                row.addElement(df.format(item.getDongia()));
                row.addElement(df.format(item.getThanhTien()));
                result.addElement(row);
                stt++;
            }
            Vector<String> columnNames = new Vector<String>();
            columnNames.addElement("STT");
            columnNames.addElement("Tên");
            columnNames.addElement("Số lượng");
            columnNames.addElement("Đơn giá");
            columnNames.addElement("Thành tiền");
            DefaultTableModel model = new DefaultTableModel(result, columnNames);     

            this.tbDanhSach.removeAll();
            this.tbDanhSach.setModel(model);        
            this.tbDanhSach.setFillsViewportHeight(true);
            this.tbDanhSach.setEnabled(false);
        }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
        
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnadd = new javax.swing.JButton();
        btnSua = new javax.swing.JButton();
        btnLuu = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        lblNgayNhap = new javax.swing.JLabel();
        lblKhachHang = new javax.swing.JLabel();
        cbbKhachHang = new javax.swing.JComboBox();
        lblNhanVienNhap = new javax.swing.JLabel();
        txtNVNhap = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        cbbTinhTrangPhieu = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        cbbKho = new javax.swing.JComboBox();
        dtcNgay_nhap = new com.toedter.calendar.JDateChooser();
        lblNgayNhap1 = new javax.swing.JLabel();
        dtcNgay_tao = new com.toedter.calendar.JDateChooser();
        jLabel3 = new javax.swing.JLabel();
        txtTongTien = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        cbbSanPham = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        txtSoLuong = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtDonGia = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtThanhTien = new javax.swing.JTextField();
        btnAddChiTiet = new javax.swing.JButton();
        btnEditct = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        btnPrevall = new javax.swing.JButton();
        txtRows = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbDanhSach = new javax.swing.JTable();
        btnnextAll = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        btnPrev = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        btnadd.setText("Thêm mới");
        btnadd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnaddActionPerformed(evt);
            }
        });

        btnSua.setText("Sửa");
        btnSua.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSuaActionPerformed(evt);
            }
        });

        btnLuu.setText("Lưu");
        btnLuu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLuuActionPerformed(evt);
            }
        });

        btnDelete.setText("Xóa");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnClose.setText("Thoát");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel9.setForeground(new java.awt.Color(102, 102, 255));
        jLabel9.setText("PHIẾU NHẬP HÀNG");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Thông tin chung"));

        lblNgayNhap.setText("Ngày nhập:");

        lblKhachHang.setText("Nhà cung cấp:");

        cbbKhachHang.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        lblNhanVienNhap.setText("Nhân viên nhập:");

        jLabel1.setText("Tình trạng phiếu:");

        cbbTinhTrangPhieu.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel8.setText("Kho:");

        cbbKho.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        dtcNgay_nhap.setDateFormatString("dd-MM-yyyy");

        lblNgayNhap1.setText("Ngày tạo phiếu:");

        dtcNgay_tao.setDateFormatString("dd-MM-yyyy");

        jLabel3.setText("Tổng tiền");

        txtTongTien.setText("0");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblNgayNhap, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dtcNgay_nhap, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbbTinhTrangPhieu, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31)
                        .addComponent(cbbKho, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblNgayNhap1, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(lblKhachHang)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbbKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(dtcNgay_tao, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTongTien))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblNhanVienNhap)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNVNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(39, 39, 39))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblNhanVienNhap)
                            .addComponent(txtNVNhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblKhachHang)
                            .addComponent(cbbKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel8)
                                .addComponent(cbbKho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblNgayNhap1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(dtcNgay_tao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(txtTongTien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(dtcNgay_nhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(cbbTinhTrangPhieu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(lblNgayNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(jLabel1)))))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Chi tiết sản phẩm"));

        jLabel4.setText("Tên sản phẩm:");

        cbbSanPham.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbbSanPham.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbbSanPhamItemStateChanged(evt);
            }
        });

        jLabel5.setText("Số lượng nhập:");

        txtSoLuong.setText("0");
        txtSoLuong.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                txtSoLuongInputMethodTextChanged(evt);
            }
        });
        txtSoLuong.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtSoLuongKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtSoLuongKeyReleased(evt);
            }
        });

        jLabel6.setText("Giá nhập:");

        txtDonGia.setText("0");
        txtDonGia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtDonGiaActionPerformed(evt);
            }
        });
        txtDonGia.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtDonGiaKeyReleased(evt);
            }
        });

        jLabel7.setText("Thành tiền:");

        txtThanhTien.setEditable(false);
        txtThanhTien.setText("0");

        btnAddChiTiet.setText("Thêm chi tiết");
        btnAddChiTiet.setEnabled(false);
        btnAddChiTiet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddChiTietActionPerformed(evt);
            }
        });

        btnEditct.setText("Sửa");
        btnEditct.setEnabled(false);
        btnEditct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditctActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(cbbSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtSoLuong, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDonGia, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnEditct, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnAddChiTiet, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtThanhTien, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(123, 123, 123))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cbbSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txtSoLuong, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(txtDonGia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(txtThanhTien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddChiTiet)
                    .addComponent(btnEditct))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Danh sách sản phẩm"));

        btnPrevall.setText("<<");
        btnPrevall.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrevallActionPerformed(evt);
            }
        });

        tbDanhSach.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbDanhSach.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbDanhSachMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbDanhSach);

        btnnextAll.setText(">>");
        btnnextAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnnextAllActionPerformed(evt);
            }
        });

        btnNext.setText(">|");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        btnPrev.setText("|<");
        btnPrev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrevActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(542, 542, 542)
                        .addComponent(btnPrev)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnPrevall)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtRows, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnnextAll)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnNext)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPrev)
                    .addComponent(btnPrevall)
                    .addComponent(txtRows, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnnextAll)
                    .addComponent(btnNext)))
        );

        btnPrint.setText("In Phiếu");
        btnPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });

        btnCancel.setText("Hủy");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.CENTER, layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.CENTER, layout.createSequentialGroup()
                                .addComponent(btnadd)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnSua)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnLuu)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnDelete)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnClose)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnPrint))
                            .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.CENTER, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.CENTER))))
                .addContainerGap())
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(24, 24, 24)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(30, 30, 30)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnadd)
                    .addComponent(btnSua)
                    .addComponent(btnLuu)
                    .addComponent(btnDelete)
                    .addComponent(btnClose)
                    .addComponent(btnPrint)
                    .addComponent(btnCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnaddActionPerformed
        // TODO add your handling code here:
        listChiTiet = new ArrayList<CChiTietHoaDon>();
        this.LoadDataTable(listChiTiet);
        hoadon = new CHoaDon();        
        this.add = true;
        this.edit = false;
        this.btnLuu.setEnabled(true);
        btnadd.setEnabled(false);
        btnSua.setEnabled(false);
        this.btnLuu.setEnabled(true);
        this.btnAddChiTiet.setEnabled(true);
        setEditable(true);
        this.clearText();
        l_ton_kho_i = new ArrayList<CTon_Kho>();
        /// danh sach kho da co. cap nhat lai ton kho
        l_ton_kho_u = new ArrayList<CTon_Kho>();
    }//GEN-LAST:event_btnaddActionPerformed

    private Boolean editRow(){
        Date d = this.dtcNgay_nhap.getDate();
        
        if(d == null){
            d = new Date();
        }
        Timestamp t = new Timestamp(d.getYear(),d.getMonth(),d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds(),0);
        this.hdCurrent.setNgayNhap(t);
        CTinhTrang tinhtrang = this.ltinh_trang.get(this.cbbTinhTrangPhieu.getSelectedIndex());
        this.hdCurrent.setTinhTrang((int)tinhtrang.getId());
        
        d = new Date();
        t = new Timestamp(d.getYear(),d.getMonth(),d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds(),0);
        this.hdCurrent.setNgaySua(t);
        CModel _model = new CModel(QuanLySieuThi.user_name);
        Boolean flag = _model.UpdateHoaDon(hdCurrent, lcthd);
        if(flag){
            JOptionPane.showMessageDialog(this, "Cap nhat thanh cong");
        }
        else{
            JOptionPane.showMessageDialog(this, "Cap nhat that bai");
        }
        return true;
    }
    
    private void txtDonGiaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDonGiaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtDonGiaActionPerformed

    private void btnAddChiTietActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddChiTietActionPerformed
        // TODO add your handling code here:
        this.addChiTiet();
        
    }//GEN-LAST:event_btnAddChiTietActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_btnCloseActionPerformed

     private CGiaBan getItemGiaBan(long san_pham_id){
        for(CGiaBan item : this.lGiaBan){
            if(item.getSanPhamId() == san_pham_id){
                return item;
            }
        }
        return null;
    }
     
    private void cbbSanPhamItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbbSanPhamItemStateChanged
        // TODO add your handling code here:
         try{
            if(evt.getStateChange() == ItemEvent.SELECTED){
                int index = this.cbbSanPham.getSelectedIndex();
                if(index >=0 && index < this.listSanPham.size()){
                    sanphamCurrent = this.listSanPham.get(index);        
                    CGiaBan gbCurrent = this.getItemGiaBan(sanphamCurrent.getId());
                    double dgnhap = sanphamCurrent.getGiaNhap();
                    if(gbCurrent!= null){
                        dgnhap =gbCurrent.getGiaNhap() ;
                    }
                    System.out.println("gia nhap : " + gbCurrent.getGiaNhap());
                    txtDonGia.setText(df.format(dgnhap));
                    if(!txtSoLuong.getText().equals("")){
                        int sl = Integer.parseInt(txtSoLuong.getText());
                        String value = txtDonGia.getText().replaceAll(",", "");
                        double don_gia = Double.parseDouble(value);
                        double thanh_tien = sl * don_gia;
                        txtThanhTien.setText(String.format("%s",df.format(thanh_tien)));
                    }
                }
            }
        }
        catch(Exception error){
            
        }
    }//GEN-LAST:event_cbbSanPhamItemStateChanged

    private void txtSoLuongInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_txtSoLuongInputMethodTextChanged
        // TODO add your handling code here:        
        try{
            if(!txtSoLuong.getText().equals("")){
                int sl = Integer.parseInt(txtSoLuong.getText());
                String value = txtDonGia.getText().replaceAll(",", "");
                double don_gia = Double.parseDouble(value);
                double thanh_tien = sl * don_gia;
                txtThanhTien.setText(String.format("%s",df.format(thanh_tien)));
            }            
        }
        catch(Exception error){
            
        }
    }//GEN-LAST:event_txtSoLuongInputMethodTextChanged

    private void txtSoLuongKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSoLuongKeyPressed
        // TODO add your handling code here:
       
    }//GEN-LAST:event_txtSoLuongKeyPressed

    private void txtSoLuongKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSoLuongKeyReleased
        // TODO add your handling code here:
         try{
            if(!txtSoLuong.getText().equals("")){
                int sl = Integer.parseInt(txtSoLuong.getText());
                String value = txtDonGia.getText().replaceAll(",", "");
                double don_gia = Double.parseDouble(value);
                double thanh_tien = sl * don_gia;
                txtThanhTien.setText(String.format("%s",df.format(thanh_tien)));
            }
            
        } catch(Exception error){
            
        }
    }//GEN-LAST:event_txtSoLuongKeyReleased

    private void txtDonGiaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDonGiaKeyReleased
        // TODO add your handling code here:
         try{
            if(!txtSoLuong.getText().equals("")){
                int sl = Integer.parseInt(txtSoLuong.getText());
                String value = txtDonGia.getText().replaceAll(",", "");
                double don_gia = Double.parseDouble(value);
                double thanh_tien = sl * don_gia;
                txtThanhTien.setText(String.format("%s",df.format(thanh_tien)));
            }
            
        } catch(Exception error){
            
        }
    }//GEN-LAST:event_txtDonGiaKeyReleased
    
    private void btnLuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuActionPerformed
        // TODO add your handling code here:
        Boolean flag = false;
        if(this.add){
            flag = addNew();
        }
        else if(this.edit){
            flag = editRow();
        }
        if(flag){
            if(this._menu != null){
                this._menu.loadTonKho();
            }
            this.add = false;
            this.edit = false;
            this.btnLuu.setEnabled(false);
            this.btnadd.setEnabled(true);
            this.btnSua.setEnabled(true);
        }
        this.setEditable(false);
    }//GEN-LAST:event_btnLuuActionPerformed


    private void btnPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrevActionPerformed
        // TODO add your handling code here:
        if(currentIndex > 0){
            currentIndex--;
            this.view(currentIndex);
        }
    }//GEN-LAST:event_btnPrevActionPerformed

    private void btnPrevallActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrevallActionPerformed
        // TODO add your handling code here:
        currentIndex = 0;
        this.view(currentIndex);
    }//GEN-LAST:event_btnPrevallActionPerformed

    private void btnnextAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnnextAllActionPerformed
        // TODO add your handling code here:
        currentIndex = numberRow -1;
        this.view(currentIndex);
    }//GEN-LAST:event_btnnextAllActionPerformed

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
        // TODO add your handling code here:
         if(currentIndex < numberRow){
            currentIndex++;
            this.view(currentIndex);
        }
    }//GEN-LAST:event_btnNextActionPerformed

    private void btnSuaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSuaActionPerformed
        // TODO add your handling code here:
        this.edit = true;
        this.add = false;
        setEditable(true);
        this.btnadd.setEnabled(false);
        this.btnSua.setEnabled(false);
        this.btnLuu.setEnabled(true);
        this.btnAddChiTiet.setEnabled(true);
    }//GEN-LAST:event_btnSuaActionPerformed

    private void tbDanhSachMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbDanhSachMouseClicked
        // TODO add your handling code here:
        //this.tbldanh_sach.setRowSelectionInterval(index, index);
        JTable table =(JTable)evt.getSource();
        Point p = evt.getPoint();
        int rowIndex = table.rowAtPoint(p);            
        if(rowIndex >=0){
            table.setRowSelectionInterval(rowIndex, rowIndex);           
        }
    }//GEN-LAST:event_tbDanhSachMouseClicked

    private void reView(int index){
        if(this.add){
            
        }
    }
    private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
        // TODO add your handling code here:
       String fileName = QuanLySieuThi.pathFolderReport + "chitietnhaphang.jrxml" ;        
       HashMap parameters = new HashMap();
        //parameters.put("title", title);
       parameters.put("p_tenkho",this.cbbKho.getSelectedItem().toString());
       parameters.put("p_tenncc",this.cbbKhachHang.getSelectedItem().toString());
       parameters.put("p_khuyenmai","");
       parameters.put("p_phieunhap","");
       Date d = this.dtcNgay_nhap.getDate();
       if(d == null){
           d = new Date();
       }
       int year = d.getYear() + 1900;
       String ngayban = d.getDate() + "-" + d.getMonth() + "-" + year ;
       parameters.put("p_ngaynhap",ngayban);       
      // parameters.put("p_nvban",this.txtNVNhap.getText());
       parameters.put("p_nvlap",this.txtNVNhap.getText());
       JRBeanCollectionDataSource collectionDataSource = new JRBeanCollectionDataSource(this.lcthd);
       FrmReport f = null;
       f = new FrmReport(collectionDataSource, fileName, parameters);
       f.setVisible(true);
    }//GEN-LAST:event_btnPrintActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        // TODO add your handling code here:
        this.view(this.currentIndex);        
        this.add = false;
        this.edit = false;
        this.btnLuu.setEnabled(false);
        this.btnadd.setEnabled(true);
        this.btnSua.setEnabled(true);
        this.btnAddChiTiet.setEnabled(false);
        this.setEditable(false);
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnEditctActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditctActionPerformed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_btnEditctActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        if(this.hdCurrent != null){
            int repley  = JOptionPane.showConfirmDialog(this, "Ban co muon xoa hoa don nay khong?");
            if(repley == JOptionPane.YES_OPTION){
                CModel _model = new CModel(QuanLySieuThi.user_name);
                Boolean flag = _model.deleteHoaDon(hdCurrent);
                if(flag){
                    JOptionPane.showMessageDialog(this, "Xoa thanh cong");
                    this.currentIndex = 0;
                    loadDataHoaDon();                    
                }
            }
        }
    }//GEN-LAST:event_btnDeleteActionPerformed
    
    private void setEditable(Boolean b){        
        this.txtNVNhap.setEditable(b);
        this.txtSoLuong.setEditable(b);        
        this.txtDonGia.setEditable(b);       
        this.cbbKhachHang.setEnabled(b);
        this.cbbKho.setEnabled(b);
        this.cbbSanPham.setEnabled(b);
        this.cbbTinhTrangPhieu.setEnabled(b);
    }
    
    private void clearText(){
      //  this.dtcNgay_nhap.setText("");       
        this.txtNVNhap.setText("");
        this.txtSoLuong.setText("1");
        this.txtDonGia.setText("0");
        txtNVNhap.setText(QuanLySieuThi.ho_ten);
    }
    private Boolean isEmpty(){
        //kiem tra cac o nhap lieu chua        
        if(this.txtNVNhap.getText().equals("")){
            JOptionPane.showMessageDialog(this, String.format("Vui lòng nhập Nhân viên nhập"));
            return true;
        }
        
        if(this.txtSoLuong.getText().equals("")){
            JOptionPane.showMessageDialog(this, String.format("Vui lòng nhập vào ô Số lượng"));
            return true;
        }
        
        if(this.txtDonGia.getText().equals("")){
            JOptionPane.showMessageDialog(this, String.format("Vui lòng nhập vào Giá nhập"));
            return true;
        }
        
        return false;
    }

    
    private Boolean addNew(){
        if(this.add == false && this.edit == false){
            return false;
        }
        if(this.listChiTiet.size() == 0){
            JOptionPane.showMessageDialog(this, "Vui lòng nhập sản phẩm cho hóa đơn");
            return false;
        }
        if(isEmpty()){
            return false;
        }
        long khachHangId = 1;
        String loai_phieu ="PN";
        String value = this.txtTongTien.getText().trim();
        value = value.replaceAll(",", "");
        Double _sum = Double.parseDouble(value);
        hoadon.setKhachHangId(khachHangId);
        hoadon.setLoaiPhieu(loai_phieu);
        long nhan_vien_lap_id =  QuanLySieuThi.user_id;
        long nhan_vien_giao_id = QuanLySieuThi.user_id;
        hoadon.setNguoiGiaoId(nhan_vien_giao_id);
        hoadon.setNguoiLapId(nhan_vien_giao_id);
        hoadon.setNguoiSua(QuanLySieuThi.user_name);
        hoadon.setNguoiTao(QuanLySieuThi.user_name);        
        hoadon.setTongTien(_sum);
        hoadon.setChietKhau(0.0);
        //listKho
        long kho_id = 0;
        int index = this.cbbKho.getSelectedIndex();
        if(index >=0 && index < listKho.size()){
            CKho _kho = listKho.get(index);
            kho_id = _kho.getId();            
        }
        hoadon.setKhoId(kho_id);
        long hoa_don_id = 1;           
        CModel _model = new CModel(QuanLySieuThi.user_name);
        _model.InsertHoaDon(hoadon, listChiTiet,l_ton_kho_i,l_ton_kho_u);       
        _model.saveHisTory();
        _model.Close();              
        this.loadDataHoaDon();
        return true;
    }
    
    private int indexKho(List<CTon_Kho> in_items,CTon_Kho tk){
        for(int i = 0;i< in_items.size();i++){
            CTon_Kho item = in_items.get(i);
            if(item.getKhoId() == tk.getKhoId() && item.getSanPhamId() == tk.getSanPhamId()){
                return i;
            }
        }
        return -1;
    }
    
    private double tongTien(List<CChiTietHoaDon> in_lCthd){
        double sum = 0;
        for(CChiTietHoaDon item : in_lCthd){
            sum += item.getThanhTien();
        }
        return sum;
    }
    
    private void addChiTiet(){     
        CChiTietHoaDon chitiet = new CChiTietHoaDon();
        long sanphamId = 1;
        CTon_Kho tkho = new CTon_Kho();
        int index = this.cbbSanPham.getSelectedIndex();
        CSanPham sanphamCurrent = new CSanPham();
        String ten_san_pham = "";
        if(index>=0 && index< listSanPham.size()){
            sanphamId = listSanPham.get(index).getId();
            sanphamCurrent = listSanPham.get(index);
            ten_san_pham = sanphamCurrent.getTenSanPham();
        }
        int soluong = Integer.parseInt(this.txtSoLuong.getText().trim());
        String value = this.txtDonGia.getText().trim();
        value = value.replaceAll(",", "");
        Double don_gia = Double.parseDouble(value);
        index = this.cbbKho.getSelectedIndex();
        if(index >=0 && index < listKho.size()){
            khoCurrent = listKho.get(index);
        }          
        tkho.setKhoId(khoCurrent.getId());
        tkho.setSanPhamId(sanphamId);
        CTon_Kho currentFind = this.tonkhoDAO.Find(tkho, listTonKho);
        if(currentFind!= null){
            tkho = currentFind;
        }
        int so_luong = Integer.parseInt(this.txtSoLuong.getText().trim());             
        Double thanh_tien = 0.0;
        if(!CKiemTra.isKiemTraSLNhapToiThieu(tkho)){
            JOptionPane.showMessageDialog(this, " San pham van con. Tu tu nhap");
            return;
        }
        if(CKiemTra.isKiemTraSoLuongNhap(tkho, so_luong)){
            chitiet.setSoLuong(so_luong);
            chitiet.setDongia(don_gia);
            chitiet.setHoaDonId(1);
            chitiet.setTenSanPham(ten_san_pham);
            thanh_tien = so_luong * don_gia;
            chitiet.setThanhTien(thanh_tien);
            chitiet.setGiamGia(0.0);
            chitiet.setTienTra(thanh_tien);
            chitiet.setTenSanPham(ten_san_pham);
            chitiet.setSanPhamId(sanphamId);
            this.listChiTiet.add(chitiet);
            Double _sum = this.tongTien(listChiTiet);
            this.txtTongTien.setText(df.format(_sum));
            this.LoadDataTable(listChiTiet);
            config = SubConfig.getInstance();  
            config.init();
            if(currentFind == null){
                currentFind = tkho;
                currentFind.setSoLuongNhap(soluong);
                currentFind.setSoLuongNhap(0);
                currentFind.setTenSanPham(ten_san_pham);
                currentFind.setTonToiDa(sanphamCurrent.getSoLgTonToiDa());
                currentFind.setTonToiThieu(sanphamCurrent.getTonToiThieu());                          
                index = this.indexKho(l_ton_kho_i, currentFind);
                if(index == -1){
                    l_ton_kho_i.add(currentFind);
                }
                else{
                    CTon_Kho tk_current = l_ton_kho_i.get(index);
                    int _sl = tk_current.getSoLuongNhap();
                    tk_current.setSoLuongNhap(soluong +_sl);
                }
            }
            else{
                int _sl =  soluong;
                index = this.indexKho(l_ton_kho_u, currentFind);
                if(index == -1){
                    _sl =  soluong + currentFind.getSoLuongNhap();
                    currentFind.setSoLuongNhap(_sl);
                    l_ton_kho_u.add(currentFind);
                }
                else{
                    CTon_Kho tk_current = l_ton_kho_u.get(index);
                    _sl = tk_current.getSoLuongNhap() + _sl;
                    tk_current.setSoLuongNhap(_sl);
                }
            }
            config.close();
        }
        else{
            JOptionPane.showMessageDialog(this, "Trong kho còn hàng không nhập sản phẩm này nữa." + tkho.getTonToiDa() );
            return;
        }
    }
    
   

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddChiTiet;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEditct;
    private javax.swing.JButton btnLuu;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnPrev;
    private javax.swing.JButton btnPrevall;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnSua;
    private javax.swing.JButton btnadd;
    private javax.swing.JButton btnnextAll;
    private javax.swing.JComboBox cbbKhachHang;
    private javax.swing.JComboBox cbbKho;
    private javax.swing.JComboBox cbbSanPham;
    private javax.swing.JComboBox cbbTinhTrangPhieu;
    private com.toedter.calendar.JDateChooser dtcNgay_nhap;
    private com.toedter.calendar.JDateChooser dtcNgay_tao;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblKhachHang;
    private javax.swing.JLabel lblNgayNhap;
    private javax.swing.JLabel lblNgayNhap1;
    private javax.swing.JLabel lblNhanVienNhap;
    private javax.swing.JTable tbDanhSach;
    private javax.swing.JTextField txtDonGia;
    private javax.swing.JTextField txtNVNhap;
    private javax.swing.JTextField txtRows;
    private javax.swing.JTextField txtSoLuong;
    private javax.swing.JTextField txtThanhTien;
    private javax.swing.JTextField txtTongTien;
    // End of variables declaration//GEN-END:variables
}
